<template>
  <div class="login">
    <div class="logo">
      <img width="300px" src="~images/hx-logo.jpg" alt=""/>
      <span></span>
    </div>
    <div class="header"></div>
    <div class="content clear">
      <div class="info">
        <div class="title">{{ showForgetPassword ? '修改密码' : $t('login.UserLogin') }}</div>
        <transition name="fade">
          <div class="tip" v-if="tipState">{{ errorInfo }}</div>
        </transition>
        <ul>
          <li>
            <span class="name"><Icon type="md-person"/>{{ $t('login.userName') }}</span>
            <div class="inputWrapper">
              <input type="text" :placeholder="$t('login.plsenterauser')" v-model="username" autocomplete="off"/>
            </div>
          </li>
          <li>
            <span class="name"><Icon type="md-key"/>{{ $t('login.password') }}</span>
            <div class="inputWrapper">
              <input type="password" :placeholder="$t('login.plsenterapass')" v-model="password" autocomplete="off"/>
            </div>
          </li>
          <li v-if="!showForgetPassword">
            <span class="name"><Icon type="md-information-circle"/>{{ $t('login.验证码') }}</span>
            <div class="inputWrapper">
              <input type="number" :placeholder="$t('请输入') + $t('login.验证码')" v-model="code" maxlength="4"
                     autocomplete="off"/>
            </div>
            <div class="verificationCode" @click="generateCode">
              <img @click="getCaptchaImage" :src="captchaImage"/>
            </div>
          </li>
          <template v-else>
            <li>
              <span class="name"><Icon type="md-information-circle"/>新密码</span>
              <div class="inputWrapper">
                <input type="password" :placeholder="$t('请输入') +'新密码'" v-model="form.newPwd" maxlength="16"
                       autocomplete="off"/>
              </div>
            </li>
            <li>
              <span class="name"><Icon type="md-information-circle"/>确认密码</span>
              <div class="inputWrapper">
                <input type="password" :placeholder="$t('请输入') + '确认密码'" v-model="form.reNewPwd" maxlength="16"
                       autocomplete="off"/>
              </div>
            </li>
            <Icon style="margin-top:20px" type="ios-checkmark-circle"/>
            密码由8-16位组成</br>
            <Icon type="ios-checkmark-circle"/>
            密码由数字(0-9)、大写字母、小写字母、特殊字符组成</br>
            <Icon type="ios-checkmark-circle"/>
            至少包含以上三种字符
          </template>

          <!--<div class="laug">
             <Row>
              <Col span='12' align="center">
                <div class="laugitem" :class="langName=='简体中文'?'active':''" @click="changeLang(1)">
                  <img width="20px" src="~images/common/china.png" alt=""/>
                  简体中文
                </div>
              </Col>
              <Col span='12' align="center">
                <div class="laugitem" :class="langName=='English'?'active':''" @click="changeLang(2)">
                  <img width="20px" src="~images/common/english.png" alt=""/>
                  English
                </div>
              </Col>
            </Row>
          </div>-->
        </ul>
        <Button style="margin-top:20px" v-if="!showForgetPassword" class="loginBtn" @click="loginMethod"
                v-on:keyup.enter="test" :loading="loading">
          {{ $t('login.login') }}
        </Button>
        <Button style="margin-top:20px" v-else class="loginBtn" @click="changePassword" :loading="loading">
          确认修改
        </Button>
        <div class="bottom clear">
          <!-- <span class="rememberPassword" :class="{ selected: isRemember }" @click="rememberPassword">
            <Icon type="md-checkbox-outline" />
            {{ $t('login.RebPassword') }}</span
          > -->
          <span v-if="!showForgetPassword" class="forgetPassword"><a @click="forgetPassword(true)">修改密码</a></span>
          <span v-else class="forgetPassword"><a @click="forgetPassword(false)">返回</a></span>
        </div>
      </div>
    </div>
    <commonModal ref="commonModal" :closable="false" :showCancel="false"></commonModal>
  </div>
</template>

<script>
import Swiper from 'swiper';
import 'swiper/dist/css/swiper.min.css';
// import '@/assets/cookie/js-cookie.js';
import * as jsBase64 from 'js-base64';
import store from '@/store/store';
import commonModal from '@/components/modalTypes/commonModal.vue';
import {TOKEN} from '@/store/types';

const isTong = process.env.NODE_ENV === 'tong';
let ksiot = '/kakone';
if (isTong) {
  ksiot = '';
}
export default {
  name: 'login',
  components: {
    commonModal,
  },
  data() {
    return {
      bgHeight: document.documentElement.clientHeight - 80,
      captchaImage: '',
      uuid: '',
      isRemember: false,
      username: '',
      password: '',
      form: {
        newPwd: '',
        reNewPwd: '',
        oldPwd: '',
      },
      code: '',
      inputCode: '',
      errorInfo: '',
      tipState: false,
      loading: false,
      langName: '',
      showForgetPassword: false,
    };
  },
  created() {
    this.getIcon();
    document.onkeydown = (event) => {
      var key = event.keyCode;
      if (key === 13) {
        this.loginMethod();
      }
    };
    // if(this.$cookies.get('zyKeSenUserName')){
    //     this.username = jsBase64.Base64.decode(this.$cookies.get('zyKeSenUserName'))
    // }
    // if(this.$cookies.get('zyKeSenPassword')){
    //     this.password = jsBase64.Base64.decode(this.$cookies.get('zyKeSenPassword'))
    // }
    if (window.localStorage.getItem('language') == 'en_US') {
      this.langName = 'English';
    } else if (window.localStorage.getItem('language') == 'zh_CN') {
      this.langName = '简体中文';
    }
  },
  mounted() {
    this.getCaptchaImage();
    // this.generateCode();
    // this.carousel();
  },
  methods: {
    forgetPassword(type) {
      this.showForgetPassword = type;
    },
    changePassword() {
      if (
          this.showForgetPassword &&
          this.form.newPwd &&
          this.form.reNewPwd && this.password && this.username
      ) {
        if (this.form.newPwd !== this.form.reNewPwd) {
          this.$Message.error(({content: "两次密码不一样，请修改！", duration: 6, closable: true}));
          return
        }
        if (!this.checkPasswordLimit()) {
          this.$Message.error(({content: "密码复杂度较低，请修改！", duration: 6, closable: true}));
          return
        }
        this.axios({
          method: 'get',
          url: "/basic/user/updatePwdPc",
          params: {
            newPwd: this.form.newPwd,
            oldPwd: this.password,
            userName: this.username
          }
        }).then(res => {
          if (res.code === 200) {
            this.$Message.success('密码修改成功，请重新登陆')
            this.showForgetPassword = false
            this.form = {
              newPwd: '',
              reNewPwd: '',
              oldPwd: '',
            };
            this.password = ""
            window.localStorage.removeItem('ziyunFactoryPortalToken')
            this.$router.push({path: '/'})
          } else {
            this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
          }
        });
      } else {
        this.$Message.error(({content: "请填写完整", duration: 6, closable: true}));
      }
    },
    checkPasswordLimit() {
      //必须包含数字(0-9)、大写字母、小写字母、特殊字符 中的至少三种
      const validObj = this.getPasswordLimitHasNumber()

      if (!validObj.isValid) {
        return false;
      } else return true
    },
    getPasswordLimitHasNumber() {
      const arrStr = [];
      const password = this.form.newPwd;
      /\d/.test(password) || arrStr.push('密码必须包含数字(0-9)');
      /[a-z]/.test(password) || arrStr.push('密码必须包含小写字母');
      /[A-Z]/.test(password) || arrStr.push('密码必须包含大写字母');
      /[!@#$%^&*]/.test(password) || arrStr.push('密码必须包含特殊字符');
      const isValid = arrStr.length <= 1;
      console.log(arrStr, isValid);
      if (password.length < 8 || password.length > 16) {
        return {
          isValid: false,
          tipStr: '密码长度为8-16位'
        }
      } else if (!isValid) {
        return {isValid, tipStr: arrStr[0]};
      } else return {isValid: true, tipStr: arrStr[0]};
    },
    changeLang(item) {
      if (item === 1) {
        window.localStorage.setItem('language', 'zh_CN');
        this.langName = '简体中文';
      } else if (item === 2) {
        window.localStorage.setItem('language', 'en_US');
        this.langName = 'English';
      } else {
        window.localStorage.setItem('language', 'zh_CN');
        this.langName = '简体中文';
      }
      window.location.reload();
    },
    getCaptchaImage() {
      this.axios({
        method: 'get',
        url: '/basic/captchaImage',
        params: {},
      }).then((res) => {
        if (res && res.code === 200) {
          this.captchaImage = 'data:image/png;base64,' + res.data.img;
          this.uuid = res.data.uuid;
        }
      });
    },
    getIcon() {
      window.localStorage.removeItem('app_download_url_waiwang');
      window.localStorage.removeItem('app_qrname_waiwang');
      window.localStorage.removeItem('app_download_url_neiwang');
      window.localStorage.removeItem('app_qrname_neiwang');
      this.axios({
        method: 'get',
        url: '/basic/sys/getSysConfig',
        params: {},
      }).then((res) => {
        if (res.code === 200) {
          if (res.data) {
            for (let item of res.data) {
              if (item.configCode == 'app_download_url_waiwang') {
                window.localStorage.setItem('app_qrname_waiwang', item.configName);
              }

              if (item.configCode == 'app_download_url_neiwang') {
                window.localStorage.setItem('app_qrname_neiwang', item.configName);
              }

              window.localStorage.setItem(item.configCode, item.configVal);
            }
          }
        } else {
          this.$Message.warning({content: res.msg, duration: 6, closable: true});
        }
      });
    },
    rememberPassword() {
      this.isRemember = !this.isRemember;
    },
    loginMethod() {
      if (!this.username) {
        this.errorInfo = this.$t('login.plsenterauser');
        this.tipState = true;
        return false;
      }
      if (!this.password) {
        this.errorInfo = this.$t('login.plsenterapass');
        this.tipState = true;
        return false;
      }

      if (!this.code) {
        this.errorInfo = '请输入验证码';
        this.tipState = true;
        return false;
      }

      let params = JSON.stringify({
        username: this.username,
        password: this.password,
        uuid: this.uuid,
        code: this.code,
        type: 'PC',
      });
      this.loading = true;
      this.axios({
        method: 'post',
        url: '/basic/token/login',
        headers: {
          token: '',
        },
        data: params,
      }).then((response) => {
        if (response.code === 200) {
          if (response.data.flag) {
            this.$refs.commonModal.showModal({
              title: '提醒',
              type: 'sure',
              desc: '超过限制密码修改时间，建议修改密码！',
              submit: () => {
                this.jumpAndCook(response);
              },
            });
          } else {
            this.jumpAndCook(response);
          }
        } else {
          this.errorInfo = response.msg;
          this.tipState = true;
          this.loading = false;
          this.getCaptchaImage();
        }
      });
    },
    jumpAndCook(response) {
      // if (this.isRemember) {
      // 	let Base64 = jsBase64.Base64;
      // 	let userName = Base64.encode(this.username);
      // 	let password = Base64.encode(this.password);
      // 	this.$cookies.set('zyKeSenUserName', userName, { expires: 30 });
      // 	this.$cookies.set('zyKeSenPassword', password, { expires: 30 });
      // } else {
      // 	this.$cookies.remove('zyKeSenUserName');
      // 	this.$cookies.remove('zyKeSenPassword');
      // }
      window.localStorage.setItem('ziyunFactoryPortalToken', response.data.token);
      window.localStorage.setItem('ziyunFactoryPortalName', response.data.realname);
      window.localStorage.setItem('ziyunFactoryUserId', response.data.userId);
      window.localStorage.setItem('ziyunFactoryUserRoleId', response.data.roleId);
      window.localStorage.setItem('ziyunFactoryUserRoleName', response.data.roleName);
      window.localStorage.setItem('ziyunFactoryUserPhone', response.data.phone);
      localStorage.setItem('KaPortalJumpMenu', '');
      store.commit(TOKEN, response.data.token);
      this.tipState = false;
      this.Jump();
    },
    Jump() {
      if (this.$route.query.redirect) {
        this.$router.push({path: decodeURIComponent(this.$route.query.redirect)});
      } else {
        this.axios({
          method: 'get',
          url: '/basic/menu/findMenuByToken',
          params: {
            menuType: 1,
          },
        }).then((res) => {
          if (res.code === 200) {
            if (res.data && res.data.length > 0) {
              if (res.data[0].url !== '###') {
                window.location.href = ksiot + res.data[0].url;
              } else {
                if (res.data[0].children && res.data[0].children.length > 0) {
                  if (res.data[0].children[0].url !== '###') {
                    window.location.href = ksiot + res.data[0].children[0].url;
                  } else {
                    if (res.data[0].children[0].children && res.data[0].children[0].children.length > 0) {
                      window.location.href = ksiot + res.data[0].children[0].children[0].url;
                    }
                  }
                }
              }
              this.$Message.success(this.$t('login.loginSucc'));
            } else {
              this.$Message.warning({content: this.$t('login.loginErr'), duration: 6, closable: true});
              this.loading = false;
              return false;
            }
          }
        });
      }
    },
    carousel() {
      let mySwiper = new Swiper('.swiper-container', {
        loop: true,
        speed: 1000,
        autoplay: {
          delay: 3000,
          disableOnInteraction: false,
        },
        pagination: {
          el: '.swiper-pagination',
          clickable: true,
        },
      });
    },
    generateCode() {
      this.generate();
      let codeArr = [
        '2',
        '3',
        '4',
        '5',
        '6',
        '7',
        '8',
        '9',
        'a',
        'b',
        'c',
        'd',
        'e',
        'f',
        'g',
        'h',
        'k',
        'm',
        'n',
        'p',
        'q',
        'r',
        's',
        't',
        'u',
        'v',
        'w',
        'x',
        'y',
        'z',
        'A',
        'B',
        'C',
        'D',
        'E',
        'F',
        'G',
        'H',
        'K',
        'L',
        'M',
        'N',
        'P',
        'Q',
        'R',
        'S',
        'T',
        'U',
        'V',
        'W',
        'X',
        'Y',
        'Z',
      ];
      this.code = [];
      for (let i = 0; i < 4; i++) {
        let num = Math.floor(Math.random() * 53);
        this.code.push(codeArr[num]);
      }
    },
    generate() {
      this.colors = [];
      for (let i = 0; i < 4; i++) {
        let obj = {};
        let r = Math.floor(Math.random() * 250);
        let g = Math.floor(Math.random() * 250);
        let b = Math.floor(Math.random() * 250);
        if (Math.random() * 10 > 5) {
          obj.rote = 'rotate(' + parseInt(Math.random() * 30) + 'deg)';
        } else {
          obj.rote = 'rotate(' + parseInt(Math.random() * 30) * -1 + 'deg)';
        }
        obj.rgb = 'rgb(' + r + ',' + g + ',' + b + ')';
        this.colors.push(obj);
      }
    },
  },
  destroyed() {
    document.onkeydown = null;
  },
};
</script>

<style lang="scss">
.login {
  background: #045eaa url(~images/background.png) no-repeat;
  background-size: cover;
  height: 100vh;
  min-height: 760px;
  position: relative;
  min-width: 1240px;

  .logo {
    position: absolute;
    left: 40px;
    top: 40px;
    display: flex;
    align-items: center;

    span {
      font-size: 40px;
      color: rgb(0, 116, 193);
    }
  }

  .header {
    width: 100%;
    height: 80px;
    line-height: 80px;

    img {
      display: inline-block;
      width: 150px;
      height: auto;
      margin-left: 45px;
      vertical-align: middle;
    }

    span {
      display: inline-block;
      vertical-align: middle;
      color: #fbfbfc;
      font-size: 18px;
      margin-left: 48px;
      position: relative;

      &::before {
        display: block;
        content: '';
        height: 30px;
        width: 1px;
        position: absolute;
        left: -20px;
        top: 25px;
        background: rgba(255, 255, 255, 0.2);
      }
    }
  }

  .content {
    width: 1326px;
    margin: 40px auto 0 auto;
    height: 80%;

    .info {
      width: 490px;
      height: 617px;
      float: right;
      background: #fff;
      border-radius: 5px;
      padding: 0 50px;
      position: relative;

      .laug {
        height: 80px;
        padding: 20px 0;

        .laugitem {
          cursor: pointer;
          height: 40px;
          line-height: 40px;
          font-size: 16px;

          img {
            position: relative;
            // top: 4px;
          }
        }

        .active {
          background-color: rgb(244, 247, 252);
        }
      }

      .title {
        margin-top: 45px;
        width: 100%;
        text-align: center;
        color: #555555;
        font-size: 24px;
        margin-bottom: 63px;
      }

      .tip {
        height: 40px;
        border: 1px solid #fb5d77;
        border-radius: 5px;
        background: #ffeef1;
        color: #fb5d77;
        line-height: 40px;
        padding-left: 50px;
        position: absolute;
        width: 340px;
        top: 96px;
        left: 50px;
      }

      ul {
        li {
          height: 80px;
          border-bottom: 1px solid rgba(153, 153, 153, 1);
          color: #777777;
          display: block;
          position: relative;

          .name {
            width: 120px;
            display: block;
            float: left;
            font-size: 14px;
            line-height: 79px;

            i {
              margin-right: 20px;
            }
          }

          .inputWrapper {
            margin-left: 100px;

            input {
              width: 66%;
              height: 79px;
              line-height: 79px;
              border: none;
            }
          }

          .verificationCode {
            position: absolute;
            right: 0;
            top: 10px;
            line-height: 56px;
            cursor: pointer;

            img {
              display: inline-block;
            }
          }
        }
      }

      .loginBtn {
        width: 390px;
        height: 60px;
        border-radius: 30px;
        background: rgba(44, 177, 251, 1);
        font-size: 20px;
        color: #fff;
        line-height: 60px;
        text-align: center;
        // margin:50px auto 0 auto;
        display: block;
        cursor: pointer;
        border: none;
      }

      .bottom {
        margin-top: 20px;

        .forgetPassword {
          float: right;
          color: #777;
          font-size: 14px;
        }

        .rememberPassword {
          float: left;
          color: #777;
          font-size: 14px;
          cursor: pointer;

          i {
            margin-right: 10px;
          }
        }

        .selected {
          i {
            color: #fff;
            background: #ffba00;
          }
        }
      }

      i {
        font-size: 16px;
      }
    }
  }

  .loginCopyRight {
    position: absolute;
    bottom: 0;
    width: 100%;
    background: rgba(255, 255, 255, 0.05);
    line-height: 40px;
    height: 40px;
    text-align: center;
    color: #9e9e9e;
    font-size: 12px;
  }

  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 0.5s;
  }

  .fade-enter,
  .fade-leave-to {
    opacity: 0;
  }
}
</style>
